﻿using System;
using System.Configuration;
using System.Collections.Specialized;
using System.Runtime.Serialization;
using SyCODE.Blog.Task;
using System.Web;
using System.IO;
using System.Xml;
using SyCODE.Component;

namespace SyCODE.Blog.Task
{
    /// <summary>
    /// 提供最新访问记录任务的实现
    /// </summary>
    [Serializable]
    public class VisitorTask : TaskBase
    {
        /// <summary>
        /// 最新访问记录任务的反序列化构造方法
        /// </summary>
        /// <param name="info">反序列化所需的数据</param>
        /// <param name="context">反序列化源的上下文</param>
        protected VisitorTask(SerializationInfo info, StreamingContext context)
        {
            Params = (NameValueCollection)info.GetValue("params", typeof(NameValueCollection));
        }

        /// <summary>
        /// 最新访问记录任务任务实现的构造函数
        /// </summary>
        /// <param name="_params">最新访问记录任务所需要的键值对数据</param>
        public VisitorTask(NameValueCollection _params)
        {
            Params = _params;
        }

        /// <summary>
        /// 最新访问记录任务的执行方法
        /// </summary>
        public override void Execute()
        {
            if (!String.IsNullOrEmpty(Params["u"]) && String.Compare(Params["u"], Params["account"], true) != 0)
            {
                string visitorPath = Path.Combine(AppPath.GetUserPhysicalPath(Params["u"]), "visitor.xml");

                if (File.Exists(visitorPath))
                {
                    //更新最新访问记录的静态XML存档文件
                    XmlDocument visitorDom = new XmlDocument();
                    visitorDom.Load(visitorPath);

                    XmlElement visitor = (XmlElement)visitorDom.DocumentElement.SelectSingleNode("body/a[@id='" + Params["account"].ToLower() + "']");
                    if (visitor == null)
                    {
                        visitor = visitorDom.CreateElement("a");
                        visitor.SetAttribute("id", Params["account"].ToLower());
                        visitor.SetAttribute("href", "/" + Params["account"].ToLower());
                        visitor.InnerText = Params["name"].ToLower();
                    }
                    else
                    {
                        visitor.InnerText = Params["name"].ToLower();
                    }

                    visitor.SetAttribute("name", DateTime.Now.ToString(StringResource.GetField("datetimeformat")));
                    XmlNode body = visitorDom.DocumentElement.SelectSingleNode("body");
                    body.AppendChild(visitor);

                    if (body.ChildNodes.Count > 20)
                    {
                        body.RemoveChild(body.ChildNodes[0]);
                    }
                    visitorDom.Save(visitorPath);
                }
            }
        }
    }
}